package com.ly.wxstore.service.weixin;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springside.modules.mapper.JsonMapper;

import com.ly.wxstore.comm.MyPage;
import com.ly.wxstore.entity.weixin.WeixinUserInfo;
import com.ly.wxstore.exception.ServerException;
import com.ly.wxstore.repository.weixin.WeixinUserInfoDao;
import com.ly.wxstore.rest.dto.ReceiveAccessTokenDto;
import com.ly.wxstore.rest.dto.WeixinUserInfoDto;
import com.ly.wxstore.utils.HttpUtil;

/**
 * 
 * 
 * @author Peter
 */
// Spring Service Bean的标识.
@Component
public class WeixinUserInfoService {

	private static Logger logger = LoggerFactory.getLogger(WeixinUserInfoService.class);

	private JsonMapper mapper = JsonMapper.nonDefaultMapper();
	
	@Autowired
	private WeixinOAuthService weixinOauthService;
	
	@Autowired
	private WeixinConf weixinConf;
	
	@Autowired
	private WeixinAccessTokenService weixinAccessTokenService;
	
	@Autowired
	private WeixinUserInfoDao weixinUserInfoDao;

	public WeixinUserInfo getById(Long id) {
		return weixinUserInfoDao.getById(id);
	}

	public List<WeixinUserInfo> getAll() {
		return weixinUserInfoDao.getAll();
	}

	/**
	 * 分页查询
	 * 
	 * @param overtime
	 * @param pageStart
	 * @param pageSize
	 * @return
	 */
	public MyPage<WeixinUserInfo> searchPage(WeixinUserInfo weixinUserInfo, int currentPage, int pageSize) {
		MyPage<WeixinUserInfo> myPage = new MyPage<WeixinUserInfo>();

		Long count = weixinUserInfoDao.searchCount(weixinUserInfo);

		int pageStart = (currentPage - 1) < 0 ? 0 : (currentPage - 1) * pageSize;
		List<WeixinUserInfo> list = weixinUserInfoDao.searchPage(weixinUserInfo, pageStart, pageSize);

		myPage.setCount(count);
		myPage.setContent(list);

		return myPage;
	}

	public void save(WeixinUserInfo weixinUserInfo) {
		weixinUserInfoDao.save(weixinUserInfo);
	}

	public void update(WeixinUserInfo weixinUserInfo) {
		weixinUserInfoDao.update(weixinUserInfo);
	}

	/**
	 * 软删除
	 */
	public void delete(Long id) {
		weixinUserInfoDao.delete(id);
	}
	
	
	
	
	// 拉取用户信息，并保存
	public String receiveWeixinUserInfo(String code) {

		//第二步：通过code换取网页授权access_token
		ReceiveAccessTokenDto receiveAccessTokenDto = weixinOauthService.receiveAccessToken(code);
		if (StringUtils.isNotBlank(receiveAccessTokenDto.getErrcode())) {
			logger.error("拉取 AccessToken 失败！---->>{code:" + code + ",errorCode:" + receiveAccessTokenDto.getErrcode() + ",errorMsg:" + receiveAccessTokenDto.getErrmsg() + "}");
		} else {

			//第四步：拉取用户信息(需scope为 snsapi_userinfo) ， 根据 Access_Token 从微信服务器拉取用户信息
			WeixinUserInfoDto weixinUserInfoDto = weixinOauthService.receiveWeixinUserInfo(receiveAccessTokenDto.getAccess_token(), receiveAccessTokenDto.getOpenid());

			if (StringUtils.isNotBlank(weixinUserInfoDto.getErrcode())) {
				logger.error("拉取用户信息失败！ request parameter -->> {access_token:" + receiveAccessTokenDto.getAccess_token() + ",openid:" + receiveAccessTokenDto.getOpenid()
						+ "} result -->> {errorCode:" + weixinUserInfoDto.getErrcode() + ",errorMsg:" + weixinUserInfoDto.getErrmsg() + "}");
			} else {

				WeixinUserInfo weixinUserInfo = dtoToEntity(weixinUserInfoDto);
				
				weixinUserInfo.setUpdateDate(new Date());
				
				// 如果数据库中已经有userinfo--更新，否则新增
				WeixinUserInfo old = weixinUserInfoDao.getByOpenId(weixinUserInfo.getOpenid());
				if (old != null) {
					//更新微信用户信息
					weixinUserInfo.setId(old.getId());
					weixinUserInfoDao.update(weixinUserInfo);
				} else {
					//新增微信用户信息
					weixinUserInfo.setWeixinPublicId(weixinConf.getPublicId());
					weixinUserInfo.setCreateDate(new Date());
					weixinUserInfoDao.save(weixinUserInfo);
				}
			}

		}

		return receiveAccessTokenDto.getOpenid();
	}
	
	/**
	 * 根据openId获取用微信信息<br/>
	 * 如果该用户信息不存在会从微信服务器拉取用户信息
	 * @param oenId
	 * @return
	 * @throws ServerException 
	 */
	public WeixinUserInfo receiveWeixinUserInfoByOpenId(String openId) throws ServerException {
		WeixinUserInfo userInfo = weixinUserInfoDao.getByOpenId(openId);
		if(userInfo==null){
			String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+weixinAccessTokenService.getAccessToken()+"&openid="+openId+"&lang=zh_CN";
			String body =HttpUtil.httpGet(url);
			WeixinUserInfoDto dto = mapper.fromJson(body, WeixinUserInfoDto.class);
			
			userInfo = dtoToEntity(dto);
			userInfo.setCreateDate(new Date());
			userInfo.setUpdateDate(new Date());
			weixinUserInfoDao.save(userInfo);
		}
		
		return userInfo;
	}
	

	private WeixinUserInfo dtoToEntity(WeixinUserInfoDto dto) {
		WeixinUserInfo info = new WeixinUserInfo();
		info.setCity(dto.getCity());
		info.setCountry(dto.getCountry());
		info.setHeadimgurl(dto.getHeadimgurl());
		
		info.setNicknameForBase64Encoder(dto.getNickname());//解决msyql插入不进Emoji表情问题
		info.setOpenid(dto.getOpenid());
		info.setPrivilege(StringUtils.join(dto.getPrivilege(), ","));
		info.setProvince(dto.getProvince());
		info.setSex(dto.getSex());
		info.setUnionid(dto.getUnionid());

		return info;
	}

	public WeixinUserInfo getByOpenIdAndWeixinPublicId(String openId, Long publicId) {
		return weixinUserInfoDao.getByOpenIdAndWeixinPublicId(openId,publicId);
	}
}
